﻿package {
	import network.ClientSocket;

	import flash.display.MovieClip;
	import flash.events.MouseEvent;

	import flash.events.Event;
	import flash.events.KeyboardEvent;

	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;

	/**
	 * @author moritzbode, simonmary
	 */



	public class SeriousGame extends MovieClip {

		public var connectScreen:MovieClip;
		public var gameOver:MovieClip;
		public var registerScreen:MovieClip;
		public var lobby:MovieClip;
		public var socket:ClientSocket;
		public var clientVersion:String="0.1";
		//public var serverURL:String="172.31.3.106";
		public var serverURL:String="127.0.0.1";
		public var features:MovieClip;
		public var players:Array;
		private var company:String;
		private var employeName:String;

		private var runner:Boolean=false;
		private var viewer:Boolean=false;
		private var defuser:Boolean=false;
		private var trapFinder:Boolean=false;
		private var riddler:Boolean=false;

		public var map:StandardMap;
		private var bombArray:Array = new Array();;
		private var defusePanel:MovieClip;
		public var spielfigur:Spielfigur;
		static var SPEED:int=8;
		private var goalReached:Boolean=false;
		private var keypressed:Boolean=false;
		private var key:int;
		private var left:uint=37;
		private var up:uint=38;
		private var right:uint=39;
		private var down:uint=40;
		static var COMPLETE:Number=197.0;
		private var startVal:Number=COMPLETE/100;
		private var proz:int=0;
		private var bomb:MovieClip;
		private var timer:Timer;
		private var defusing:Boolean = false;

		
		private var bombNr:int = -1;
		private var received:Boolean = true;
		private var changeFeatureByMyOwn : String = "";
		private var defusedBomb:int=0;
		private var defuseBombNr:int = -1;
		private var frameCounter:int = 0;
		private var sendingBombs:Boolean = false;
		
		private var gameTimer:int = 0;
		private var timerPanel:MovieClip;

		private var quizTimer:Timer;
		private var quizenginge: Quiz;
		private var quizQuestionTimer : Timer;
		private var questionTime:int = 0;
		private var waitingquiz : WaitingQuiz;
		private var quizTime: Boolean = false;
		private var quizNoQuestionSelected:Boolean = true;
		private var sichtfeldExtra : SichtfeldExtra;
		private var sichtfeld : Sichtfeld;
		private var points:int = 0;
		
		private var bombAlreadyExploded:Boolean = false;
		private var goalAlreadyReached:Boolean = false;
		
		public function SeriousGame() {
			this.init();
		}
		private function init():void {
			this.stage.scaleMode = "noBorder";
			
			this.features.visible = false;
			this.gameOver.visible = false;
			this.registerScreen.visible = false;
			this.registerScreen.register.addEventListener(MouseEvent.CLICK, registerClick);
			this.lobby.visible=false;
			//this.lobby.trapCheckbox.checkBox.addEventListener(MouseEvent.CLICK, featureChangedLobby);
			
			this.lobby.quizCheckbox.label.text="Raetsel loesen";
			//this.lobby.quizCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.seeCheckbox.label.text="Sehen";
			//this.lobby.seeCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.walkCheckbox.label.text="Laufen";
			//this.lobby.walkCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.deactivateCheckbox.label.text="Fallen entschaerfen";
			//this.lobby.deactivateCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible=false;
			this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible=false;

			this.lobby.connectedPlayers.connectedPlayer2.textField.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.features.raetsel.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.features.fallen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.features.entschaerfen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.features.sehen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.features.laufen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer2.ready.visible=false;

			this.lobby.connectedPlayers.connectedPlayer3.textField.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.features.raetsel.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.features.fallen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.features.entschaerfen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.features.sehen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.features.laufen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer3.ready.visible=false;

			this.lobby.connectedPlayers.connectedPlayer4.textField.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.features.raetsel.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.features.fallen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.features.entschaerfen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.features.sehen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.features.laufen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer4.ready.visible=false;

			this.lobby.connectedPlayers.connectedPlayer5.textField.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.features.raetsel.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.features.fallen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.features.entschaerfen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.features.sehen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.features.laufen.visible=false;
			this.lobby.connectedPlayers.connectedPlayer5.ready.visible=false;

			this.lobby.readyButton.addEventListener(MouseEvent.CLICK,readyButtonClick);
			this.lobby.readyButton.enabled = false;
			connectToServer();
		}

		private function connectToServer():void {
			if (socket==null) {

				socket=new ClientSocket(this);


				// Verbinden zum Server
				socket.connect(serverURL, 6112, clientVersion);

			}
		}

		private function readyButtonClick(event : MouseEvent):void {
			if (this.lobby.connectedPlayers.connectedPlayer1.ready.currentFrame==1) {
//				this.lobby.trapCheckbox.checkBox.addEventListener(MouseEvent.CLICK, featureChangedLobby);
//				this.lobby.trapCheckbox.checkBox.disabled.visible = false;
				this.socket.send("ready\n");
			} else{
				this.socket.send("unready\n");
			}
		}

		private function featureChangedLobby(event : MouseEvent):void {
			this.lobby.error.text = "";
			switch (event.currentTarget) {
				case this.lobby.trapCheckbox.checkBox :
					if (this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible) {
						//this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible=false;
						//this.lobby.trapCheckbox.checkBox.gotoAndStop(1);
						trace("deselect trap");
						this.socket.send("deselectFeature\n");
						this.socket.send("trap\n");
						this.changeFeatureByMyOwn = "trap";
					}else{
						this.socket.send("selectFeature\n");
						this.socket.send("trap\n");
						this.changeFeatureByMyOwn = "trap";
						//this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible=true;
						//this.lobby.trapCheckbox.checkBox.gotoAndStop(2);
					}
					break;
				case this.lobby.quizCheckbox.checkBox :
					if (this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible) {
						this.socket.send("deselectFeature\n");
						this.socket.send("quiz\n");
						this.changeFeatureByMyOwn = "quiz";
						//this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible=false;
					} else {
						this.socket.send("selectFeature\n");
						this.socket.send("quiz\n");
						this.changeFeatureByMyOwn = "quiz";
						//this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible=true;
					}
					break;
				case this.lobby.seeCheckbox.checkBox :
					if (this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible) {
						this.socket.send("deselectFeature\n");
						this.socket.send("see\n");
						this.changeFeatureByMyOwn = "see";
						//this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible=false;
					} else {
						this.socket.send("selectFeature\n");
						this.socket.send("see\n");
						this.changeFeatureByMyOwn = "see";
						//this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible=true;
					}
					break;
				case this.lobby.walkCheckbox.checkBox :
					if (this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible) {
						this.socket.send("deselectFeature\n");
						this.socket.send("walk\n");
						this.changeFeatureByMyOwn = "walk";
						//this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible=false;
					} else {
						this.socket.send("selectFeature\n");
						this.socket.send("walk\n");
						this.changeFeatureByMyOwn = "walk";
						//this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible=true;
					}
					break;
				case this.lobby.deactivateCheckbox.checkBox :
					if (this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible) {
						this.socket.send("deselectFeature\n");
						this.socket.send("deactivate\n");
						this.changeFeatureByMyOwn = "deactivate";
						//this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible=false;
					} else {
						this.socket.send("selectFeature\n");
						this.socket.send("deactivate\n");
						this.changeFeatureByMyOwn = "deactivate";
						//this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible=true;
					}
					break;
				default :
			}
		}

		private function registerClick(event : MouseEvent):void {
			var name:String=this.registerScreen.inputName.text;
			var company:String=this.registerScreen.inputCompany.text;
			if (name==""||company=="") {
				trace("falschtest");
			} else {
				this.socket.send("login\n");
				this.socket.send(name+"\n");
				this.socket.send(company+"\n");
				
				this.employeName=name;

				this.company=company;
				//
				//this.lobby.visible = true;
				//
				////after register code
				//this.lobby.connectedPlayers.connectedPlayer1.textField.htmlText = name + " (<i>" + company +"</i>)";
				//
				//this.registerScreen.visible = false;
			}

		}

		public function setPlayers(array:Array):void {
			this.players=array;
		}

		public function getPlayers():Array {
			return this.players;
		}

		public function showLobby() : void {
			var next:int = 2;
			var tempArray:Array = new Array();
			var me:Player = new Player();
			me.setCompany(company);
			me.setName(name);
			tempArray.push(me);
			for(var i:int;i<this.players.length;i++){
				var spieler:Player = Player(this.players[i]);
				if(spieler!=null){
					if(spieler.getName() != this.employeName){
						switch(next){
							case 2:
								this.lobby.readyButton.enabled = true;
								this.lobby.connectedPlayers.connectedPlayer2.textField.text = spieler.getName() + " (" + spieler.getCompany() +")";
								this.lobby.connectedPlayers.connectedPlayer2.textField.visible = true;
								this.lobby.connectedPlayers.connectedPlayer2.ready.visible = true;
								break;
							case 3 :
								this.lobby.connectedPlayers.connectedPlayer3.textField.text=spieler.getName()+" ("+spieler.getCompany()+")";
								this.lobby.connectedPlayers.connectedPlayer3.textField.visible=true;
								this.lobby.connectedPlayers.connectedPlayer3.ready.visible=true;
								break;
							case 4 :
								this.lobby.connectedPlayers.connectedPlayer4.textField.text=spieler.getName()+" ("+spieler.getCompany()+")";
								this.lobby.connectedPlayers.connectedPlayer4.textField.visible=true;
								this.lobby.connectedPlayers.connectedPlayer4.ready.visible=true;
								break;
							case 5 :
								this.lobby.connectedPlayers.connectedPlayer5.textField.visible=true;
								this.lobby.connectedPlayers.connectedPlayer5.ready.visible=true;
								this.lobby.connectedPlayers.connectedPlayer5.textField.text=spieler.getName()+" ("+spieler.getCompany()+")";
								break;

							default :
						}
						tempArray.push(spieler);
						next++;
					} else {
						trace("setMe: "+spieler.getName() + " " + spieler.getCompany());
						this.lobby.connectedPlayers.connectedPlayer1.textField.text=spieler.getName()+" ("+spieler.getCompany()+")";
					}
				}
			}
			var length:int = 5-tempArray.length;
			for (var j : int = 0; j < length; j++) {
				tempArray.push(null);
			}
			this.players = tempArray;
			trace(this.players);
			this.registerScreen.visible = false;
			this.lobby.visible = true;
		}
		
		public function playerJoinedGame(spieler : Player, numberOfPlayer:int) : void {
			this.lobby.readyButton.enabled = true;
			switch(numberOfPlayer) {
							case 2:
								this.lobby.connectedPlayers.connectedPlayer2.textField.text = spieler.getName() + " (" + spieler.getCompany() +")";
								this.lobby.connectedPlayers.connectedPlayer2.textField.visible = true;
								this.lobby.connectedPlayers.connectedPlayer2.ready.visible = true;
								break;
							case 3:
								this.lobby.connectedPlayers.connectedPlayer3.textField.text = spieler.getName() + " (" + spieler.getCompany() +")";
								this.lobby.connectedPlayers.connectedPlayer3.textField.visible = true;
								this.lobby.connectedPlayers.connectedPlayer3.ready.visible = true;
								break;
							case 4:
								this.lobby.connectedPlayers.connectedPlayer4.textField.text = spieler.getName() + " (" + spieler.getCompany() +")";
								this.lobby.connectedPlayers.connectedPlayer4.textField.visible = true;
								this.lobby.connectedPlayers.connectedPlayer4.ready.visible = true;
								break;
							case 5:
								this.lobby.connectedPlayers.connectedPlayer5.textField.visible = true;
								this.lobby.connectedPlayers.connectedPlayer5.ready.visible = true;
								this.lobby.connectedPlayers.connectedPlayer5.textField.text = spieler.getName() + " (" + spieler.getCompany() +")";
								break;	
							
							default:
			}
		}
		public function initLevel():void {
			this.lobby.visible = false;
			this.initFeatures();
			this.map = new StandardMap();
			this.map.x = -1440;
			this.map.y = -1412;
			if (this.runner) {
				stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);
				stage.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
				stage.addEventListener(Event.ENTER_FRAME, moveCharacter);
			}

			stage.addChild(this.map);


			if (this.viewer) {
				//großes sichtfeld
				this.sichtfeldExtra = new SichtfeldExtra();
				stage.addChild(sichtfeldExtra);
			} else {
				//kleines sichtfeld
				this.sichtfeld = new Sichtfeld();
				stage.addChild(sichtfeld);

			}
			this.features.visible = true;
			this.stage.addChild(this.features);
			if (this.defuser) {
				//eventListener
				stage.addEventListener(KeyboardEvent.KEY_DOWN, defuseDown);
			}
			

			if(riddler){
				this.quizenginge = new Quiz();
				this.quizenginge.setSeriuosGame(this);
				this.quizenginge.x = 100;
				this.quizenginge.y = 100;
				this.quizTimer = new Timer(60000,1);
				this.quizTimer.addEventListener(TimerEvent.TIMER_COMPLETE,nextQuiz);
				this.quizQuestionTimer = new Timer(1000,60);
				this.quizQuestionTimer.addEventListener(TimerEvent.TIMER_COMPLETE, questionTimeComplete);
				this.quizQuestionTimer.addEventListener(TimerEvent.TIMER, quistionTimeTick);
				trace("startQuizTimer");
				this.quizTimer.start();
			}else{
				this.waitingquiz = new WaitingQuiz();
				this.waitingquiz.x = 100;
				this.waitingquiz.y = 100;
			}

			if (this.trapFinder) {
				setBombs();

			}
			this.spielfigur = new Spielfigur();
			this.spielfigur.x = 400;
			this.spielfigur.y = 300;
			this.spielfigur.arme.stop();
			this.spielfigur.fuesse.stop();
			this.spielfigur.koerper.stop();
			stage.addChild(this.spielfigur);
			
			this.defusePanel = new DefusePanel();
			this.defusePanel.x = 400;
			this.defusePanel.y = 200;
			this.defusePanel.visible = false;
			this.defusePanel.defuseText.selectable = false;
			stage.addChild(this.defusePanel);
			
			this.timerPanel = new GameTimerPanel();
			this.timerPanel.x = 30;
			this.timerPanel.y = 20;
			this.timerPanel.timePanel.selectable = false;
			stage.addChild(this.timerPanel);
		}
		
		private function setBombs():void {
			var prozent:Number = 5.0;
			var walkableFields:Array = this.map.getWalkableFields();
			for(var yVal:int = 0; yVal < walkableFields.length; yVal++) {
				for(var xVal:int = 0; xVal < walkableFields[yVal].length; xVal++) {
					if(walkableFields[yVal][xVal] == 1) {
						var randomNum:Number = Math.random() * 100;
						if(randomNum <= prozent) {
							//senden bombe setzen mit xVal und yVal
							if(!this.sendingBombs) {
								this.socket.send("setBomb\n");
								this.sendingBombs = true;
							}
							this.socket.send(xVal+":"+yVal+"\n");
						}
					}
				}
			}
			this.socket.send("setBombFinished\n");
			this.sendingBombs = false;
			
		}
		public function putBomb(xVar:int, yVar:int):void {
			var bomb:MovieClip = new Bombe();
			if(!this.trapFinder) {
				bomb.visible = false;
			}
			bomb.x = 48 * xVar + 24;
			bomb.y = 48 * yVar + 24;
			bombArray.push(bomb);
			this.map.addChild(bomb);
		}

		private function quistionTimeTick(event : TimerEvent) : void {
			
				this.questionTime--;
				this.quizenginge.setTextForCountdown(this.questionTime+"");
			
			
			
		}

		private function questionTimeComplete(event : TimerEvent) : void {
			trace("question Time abgelaufen");
			if(this.quizNoQuestionSelected){
				this.socket.send("quizTimeEnded\n");
				this.quizQuestionTimer.reset();
			}
		}

		public function questionTimeCompleteCorrectUnCorrect(correct:String):void{
			if(correct == "Correct"){
				this.socket.send("questionCorrect\n");
			}
			this.socket.send("quizTimeEnded\n");
		}
		private function nextQuiz(event : TimerEvent) : void {
			trace("showQuiz");
			this.socket.send("quizTimeStarted\n");
			
		}

		//		public function initPlayer():void {
//			if (runner) {
//				//eventlistener fürs laufen
//			}
//			if (viewer) {
//				//großes sichtfeld
//			} else {
//				//kleines sichtfeld
//			}
//			if (defuser) {
//				//eventListener
//			}
//			if (trapFinder) {
//				//bomben sichtbar
//			}
//			if (riddler) {
//			}
//
//
//		}
		//player functions
		function keyDownListener(e:KeyboardEvent) {
			this.key = e.keyCode;
			keypressed=true;
		}
		function keyUpListener(e:KeyboardEvent) {
			keypressed=false;
			spielfigur.arme.stop();
			spielfigur.fuesse.stop();
		}
		function defuseDown(e:KeyboardEvent) {
			this.key = e.keyCode;
			if(this.key == 17 && !defusing) {
				this.defuseBombNr = bombDefusable();
				trace("This.DefuseBombNr in defuseDown: "+this.defuseBombNr);
				if(defuseBombNr != -1) {
					defuse(defuseBombNr);
					
				}
			}
		}
		
		function moveCharacter(e:Event) {
			
			this.frameCounter++;
			if(!this.quizTime){
				if (this.runner && keypressed && (this.key == left || this.key == right || this.key == up || this.key == down) && this.frameCounter % 2 == 0) {
					trace("walking");
					bombNr = bombCollision();
					var rotationPlayer:int = 0;
					var newPos:int = 0;
					if (this.key==left) {
						if (collisionDetection(-SPEED ,0)) {
							rotationPlayer = -90;
							newPos=map.x+SPEED;
							trace("sending move");
							this.socket.send("move\n");
							this.socket.send(newPos+":"+map.y+":"+rotationPlayer+":"+bombNr+"\n");
							doMove(newPos, map.y, rotationPlayer, bombNr);
							
						}
						
					} else if (this.key == right) {
						if (collisionDetection(SPEED,0)) {
							trace("1.sending BombNumber: "+bombNr);
							rotationPlayer = 90;
							newPos=map.x-SPEED;
							this.socket.send("move\n");
							this.socket.send(newPos+":"+map.y+":"+rotationPlayer+":"+bombNr+"\n");
							doMove(newPos, map.y, rotationPlayer, bombNr);
						}
			
					} else if (this.key == up) {
						if (collisionDetection(0, -SPEED)) {
							rotationPlayer = 0;
							newPos=map.y+SPEED;
							this.socket.send("move\n");
							this.socket.send(map.x+":"+newPos+":"+rotationPlayer+":"+bombNr+"\n");
							doMove(map.x, newPos, rotationPlayer, bombNr);
						}
					} else if (this.key == down) {
						if (collisionDetection(0, SPEED)) {
							rotationPlayer = 180;
							newPos=map.y-SPEED;
							this.socket.send("move\n");
							this.socket.send(map.x+":"+newPos+":"+rotationPlayer+":"+bombNr+"\n");
							doMove(map.x, newPos, rotationPlayer, bombNr);
						}
					}
					//bomb collision später
				}
			}
		}

		public function doMove(xVal:int, yVal:int, rot:int, bombNummer:int):void {
			trace("2.receiving bombnumber: "+bombNummer);
			this.received = true;
			map.x = xVal;
			map.y = yVal;
			spielfigur.rotation = rot;
			moveAni();
			if (bombNummer != -1&&!this.bombAlreadyExploded) {
				trace("Exploding bomb with Number: "+bombNummer);
				if(this.runner){
					this.socket.send("bombExploded\n");
				}
				explodeBomb(bombNummer);
				this.bombAlreadyExploded = true;
			}
			if (goalReached&&!this.goalAlreadyReached) {
				trace("goalReached");
				this.socket.send("goalReached\n");
				this.goalAlreadyReached = true;
			}

		}
		private function explodeBomb(bombVal:int):void {
			trace("BOOOOOOOM");
			var bombExplosion:MovieClip = new BombExplosion();
			bombExplosion.x=400;
			bombExplosion.y=300;
			stage.addChild(bombExplosion);
			var bombs:Array=getBombArray();
			bomb = bombs[bombVal];
			bomb.visible=false;
			this.updateBombArray(bombVal);
		}
		private function moveAni():void {
			if(spielfigur.arme.currentFrame >= 41) {
				spielfigur.arme.gotoAndStop(1);
			} else {
				spielfigur.arme.nextFrame();
			}
			if(spielfigur.fuesse.currentFrame >= 41) {
				spielfigur.fuesse.gotoAndStop(1);
			} else {
				spielfigur.fuesse.nextFrame();
			}
			if(spielfigur.koerper.currentFrame >= 41) {
				spielfigur.koerper.gotoAndStop(1);
			} else {
				spielfigur.koerper.nextFrame();
			}
		}
		private function collisionDetection(newX:int, newY:int):Boolean {
			var mX:int = -1 * map.x + spielfigur.x + newX;
			var mY:int = -1 * map.y + spielfigur.y + newY;
			
			while(mX % 48 != 0) {
				mX--;
			}
			var xPosTile:int = mX / 48;
			while(mY % 48 != 0) {
				mY--;
			}
			var yPosTile:int = mY / 48;
			//trace("xPosTile:"+xPosTile+"  yPosTile:"+yPosTile);
			var mapArray:Array = map.getFields();
			//wenn das neue Feld Sand ist (=7)
			
			if(mapArray[yPosTile][xPosTile] == null) {
				return false;
			}
			if(mapArray[yPosTile][xPosTile] == 99) {
				goalReached = true;
			}
			if(mapArray[yPosTile][xPosTile] == 0) {
				return true;	
			} else {
				return false;
			}
			
		}

		private function bombCollision():int {
			var bombs:Array=getBombArray();

			for (var anz:int = 0; anz < bombs.length; anz++) {
				if (bombs[anz].bomb.hitTestObject(spielfigur)) {
					trace("Bombe Kollision: "+bombs[anz]+" mit der Nummer:"+anz);
					return anz;
				}
			}
			return -1;
		}
		public function cleanupGame(success:String):void {
			if(success == "successful"){
				this.gameOver.textField.text = "Herzlichen Glueckwunsch ihr habt das Spiel erfolgreich beendet.";
			}else if(success == "unsuccessful"){
				this.gameOver.textField.text = "Ihr habt das Spiel nicht erfolgreich beendet.";
				
			}
			this.features.visible = false;
			this.gameOver.punkte.text = "Punkte: " + this.points;
			var std:int = int(this.gameTimer / 3600); 
            var min:int = int(int(this.gameTimer % 3600)/60); 
            var sec:int = this.gameTimer % 60;
			this.gameOver.zeit.text = "Zeit: " + (std < 9 ? "0" + std : std) + ":" + (min < 9 ? "0" + min : min) + ":" + (sec < 9 ? "0" + sec : sec);
			
			stage.removeChild(this.timerPanel);
			stage.removeChild(spielfigur);
			stage.removeChild(map);
			if (this.viewer) {
				
				stage.removeChild(sichtfeldExtra);
			} else {
				
				stage.removeChild(sichtfeld);

			}
			if (this.runner) {
				stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);
				stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpListener);
				stage.removeEventListener(Event.ENTER_FRAME, moveCharacter);
			}
			if(this.riddler) {
				this.quizTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,nextQuiz);
			this.quizQuestionTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, questionTimeComplete);
			this.quizQuestionTimer.removeEventListener(TimerEvent.TIMER, quistionTimeTick);
			}
			
			this.gameOver.joinGame.addEventListener(MouseEvent.CLICK,joinNewGameClick);
			this.gameOver.visible = true;
			
			trace("fertig");
			//stage.removeEventListener(Event.ENTER_FRAME, moveCharacter);
		}
		//////


		public function bombDefusable():int {
			var bombs:Array = this.getBombArray();
			var playerRect:Rectangle = new Rectangle(this.spielfigur.x - 20, this.spielfigur.y - 20, 40, 40);
			for (var anz:int = 0; anz < bombs.length; anz++) {
				var nX:int = map.x + bombs[anz].x - 30;
				var nY:int = map.y + bombs[anz].y - 30;
				var bombRect:Rectangle = new Rectangle(nX, nY, 60, 60);
				trace(bombRect.x+" "+bombRect.y);
				if (bombRect.intersects(playerRect)) {
					trace("bomb defusable");
					return anz;
				}
			}
			return -1;

		}
		
		public function defuse(nr:int):void {
			if(nr != 0) {
				this.socket.send("defuse\n");
				trace("sending defuseNumber:" + nr);
				this.socket.send(nr+"\n");
			}

		}
		public function doDefuse(bombNumber):void {
			this.defusedBomb = bombNumber;
			trace("Defuse Bomb with number: "+bombNumber);
			var bombs:Array=getBombArray();
			bomb = bombs[bombNumber];
			this.defusePanel.visible = true;
			this.defusePanel.balken.width=2;

			timer=new Timer(50,0);
			timer.addEventListener("timer", count);
			defusing=true;
			timer.start();
			stage.addEventListener(Event.ENTER_FRAME, stopTimer);
			
		}
		private function count(event:TimerEvent) {
			proz++;
			this.defusePanel.balken.width=startVal*proz;
			this.defusePanel.defuseText.text="defusing bomb... "+proz+"%";
		}
		private function stopTimer(e:Event) {
			if (proz>=100) {
				timer.stop();
				//timer.reset();
				proz=0;
				this.defusePanel.defuseText.text="DONE!";
				this.defusePanel.defuseText.text = "";
				stage.focus=null;
				stage.addEventListener(Event.ENTER_FRAME, defusingComplete);

			}

		}
		private function defusingComplete(e:Event) {
			//if(e.keyCode == 13) {
			stage.removeEventListener(Event.ENTER_FRAME, defusingComplete);
			cleanDefused();
			//}
		}
		private function cleanDefused():void {			
			this.defusePanel.visible=false;
			stage.removeEventListener(Event.ENTER_FRAME, stopTimer);
			bomb.visible=false;
			this.updateBombArray(defusedBomb);
			defusing=false;
			this.socket.send("defused\n");
			//stage.addEventListener(Event.ENTER_FRAME, moveCharacter);
		}

		public function playerIsReady(userForFeatureTaken : String) : void {
			var playerIndex:int = 0;
			trace(this.getPlayers());
			for each (var spieler : Player in this.players) {
				if(spieler != null && userForFeatureTaken == spieler.getName()){
					playerIndex = this.players.indexOf(spieler);
					trace("setPlayerIndex: " + playerIndex);
					break;
				}
			}
			switch(playerIndex) {
				case 0:
					this.lobby.connectedPlayers.connectedPlayer1.ready.gotoAndStop(2);
					break;
				case 1:
					this.lobby.connectedPlayers.connectedPlayer2.ready.gotoAndStop(2);
					break;
				case 2:
					this.lobby.connectedPlayers.connectedPlayer3.ready.gotoAndStop(2);
					break;
				case 3:
					this.lobby.connectedPlayers.connectedPlayer4.ready.gotoAndStop(2);
					break;
				case 4:
					this.lobby.connectedPlayers.connectedPlayer5.ready.gotoAndStop(2);
					break;
				default:
			}
		}

		public function playerIsNotReady(userForFeatureTaken : String) : void {
			var playerIndex:int = 0;
			for each (var spieler : Player in this.players) {
				if(spieler != null &&userForFeatureTaken == spieler.getName()){
					playerIndex = this.players.indexOf(spieler);
					break;
				}
			}
			switch(playerIndex) {
				case 0:
					this.lobby.connectedPlayers.connectedPlayer1.ready.gotoAndStop(1);
					break;
				case 1:
					this.lobby.connectedPlayers.connectedPlayer2.ready.gotoAndStop(1);
					break;
				case 2:
					this.lobby.connectedPlayers.connectedPlayer3.ready.gotoAndStop(1);
					break;
				case 3:
					this.lobby.connectedPlayers.connectedPlayer4.ready.gotoAndStop(1);
					break;
				case 4:
					this.lobby.connectedPlayers.connectedPlayer5.ready.gotoAndStop(1);
					break;
				default:
			}
		}

		public function playerLoggedIn() : void {
			this.socket.send("joinGame\n");
		}

		public function playersAllReady() : void {
			this.lobby.trapCheckbox.checkBox.disabled.visible = false;
			this.lobby.trapCheckbox.checkBox.addEventListener(MouseEvent.CLICK, featureChangedLobby);
			
			this.lobby.quizCheckbox.checkBox.disabled.visible = false;
			this.lobby.quizCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.seeCheckbox.checkBox.disabled.visible =false;
			this.lobby.seeCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.walkCheckbox.checkBox.disabled.visible =false;
			this.lobby.walkCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);

			this.lobby.deactivateCheckbox.checkBox.disabled.visible =false;
			this.lobby.deactivateCheckbox.checkBox.addEventListener(MouseEvent.CLICK,featureChangedLobby);
		}

		public function featureTaken(userForFeatureTaken : String, feature : String) : void {
			var playerIndex:int = 0;
			for each (var spieler : Player in this.players) {
				if(spieler != null &&userForFeatureTaken == spieler.getName()){
					playerIndex = this.players.indexOf(spieler);
					break;
				}
			}
			
			switch(playerIndex) {
				case 0:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible=true;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible=true;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible=true;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible=true;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible=true;
					}
					
					break;
				case 1:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer2.features.fallen.visible=true;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer2.features.raetsel.visible=true;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer2.features.sehen.visible=true;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer2.features.laufen.visible=true;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer2.features.entschaerfen.visible=true;
					}
					break;
				case 2:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer3.features.fallen.visible=true;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer3.features.raetsel.visible=true;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer3.features.sehen.visible=true;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer3.features.laufen.visible=true;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer3.features.entschaerfen.visible=true;
					}
					break;
				case 3:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer4.features.fallen.visible=true;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer4.features.raetsel.visible=true;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer4.features.sehen.visible=true;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer4.features.laufen.visible=true;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer4.features.entschaerfen.visible=true;
					}
					break;
				case 4:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer5.features.fallen.visible=true;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer5.features.raetsel.visible=true;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer5.features.sehen.visible=true;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer5.features.laufen.visible=true;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer5.features.entschaerfen.visible=true;
					}
					break;
				default:
			}
		}

		public function deactivateCheckBoxes(feature : String) : void {
			if(feature=="trap"){
				if(this.changeFeatureByMyOwn == "trap"){
					this.trapFinder =true;
					this.lobby.trapCheckbox.checkBox.gotoAndStop(2);
				}else{
					this.lobby.trapCheckbox.checkBox.disabled.visible = true;
				}
			}else if(feature == "quiz"){
				if(this.changeFeatureByMyOwn == "quiz"){
					this.riddler = true;
					this.lobby.quizCheckbox.checkBox.gotoAndStop(2);
				}else{
					this.lobby.quizCheckbox.checkBox.disabled.visible = true;
				}
			}else if(feature == "see"){
				if(this.changeFeatureByMyOwn == "see"){
					this.viewer = true;
					this.lobby.seeCheckbox.checkBox.gotoAndStop(2);
				}else{
					this.lobby.seeCheckbox.checkBox.disabled.visible = true;
				}
			}else if(feature == "walk"){
				if(this.changeFeatureByMyOwn == "walk"){
					this.runner = true;
					this.lobby.walkCheckbox.checkBox.gotoAndStop(2);
				}else{
					this.lobby.walkCheckbox.checkBox.disabled.visible = true;
				}
			}else if(feature == "deactivate"){
				if(this.changeFeatureByMyOwn == "deactivate"){
					this.defuser =true;
					this.lobby.deactivateCheckbox.checkBox.gotoAndStop(2);
				}else{
					this.lobby.deactivateCheckbox.checkBox.disabled.visible = true;
				}
			}
			this.changeFeatureByMyOwn = "";
		}

		public function featureUntaken(userForFeatureTaken : String, feature : String) : void {
			var playerIndex:int = 0;
			for each (var spieler : Player in this.players) {
				if(spieler != null && userForFeatureTaken == spieler.getName()){
					playerIndex = this.players.indexOf(spieler);
					break;
				}
			}
			
			switch(playerIndex) {
				case 0:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer1.features.fallen.visible=false;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer1.features.raetsel.visible=false;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer1.features.sehen.visible=false;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer1.features.laufen.visible=false;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer1.features.entschaerfen.visible=false;
					}
					
					break;
				case 1:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer2.features.fallen.visible=false;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer2.features.raetsel.visible=false;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer2.features.sehen.visible=false;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer2.features.laufen.visible=false;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer2.features.entschaerfen.visible=false;
					}
					break;
				case 2:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer3.features.fallen.visible=false;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer3.features.raetsel.visible=false;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer3.features.sehen.visible=false;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer3.features.laufen.visible=false;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer3.features.entschaerfen.visible=false;
					}
					break;
				case 3:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer4.features.fallen.visible=false;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer4.features.raetsel.visible=false;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer4.features.sehen.visible=false;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer4.features.laufen.visible=false;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer4.features.entschaerfen.visible=false;
					}
					break;
				case 4:
					if(feature=="trap"){
						this.lobby.connectedPlayers.connectedPlayer5.features.fallen.visible=false;
					}else if(feature == "quiz"){
						this.lobby.connectedPlayers.connectedPlayer5.features.raetsel.visible=false;
					}else if(feature == "see"){
						this.lobby.connectedPlayers.connectedPlayer5.features.sehen.visible=false;
					}else if(feature == "walk"){
						this.lobby.connectedPlayers.connectedPlayer5.features.laufen.visible=false;
					}else if(feature == "deactivate"){
						this.lobby.connectedPlayers.connectedPlayer5.features.entschaerfen.visible=false;
					}
					break;
				default:
			}
		}

		public function activateCheckBoxes(feature : String) : void {
			if(feature=="trap"){
				if(this.changeFeatureByMyOwn == "trap"){
					this.trapFinder = false;
					this.lobby.trapCheckbox.checkBox.gotoAndStop(1);
				}else{
					
					this.lobby.trapCheckbox.checkBox.disabled.visible = false;
				}
			}else if(feature == "quiz"){
				if(this.changeFeatureByMyOwn == "quiz"){
					this.riddler = false;
					this.lobby.quizCheckbox.checkBox.gotoAndStop(1);
				}else{
					
					this.lobby.quizCheckbox.checkBox.disabled.visible = false;
				}
			}else if(feature == "see"){
				if(this.changeFeatureByMyOwn == "see"){
					this.viewer = false;
					this.lobby.seeCheckbox.checkBox.gotoAndStop(1);
				}else{
					this.lobby.seeCheckbox.checkBox.disabled.visible = false;
				}
			}else if(feature == "walk"){
				if(this.changeFeatureByMyOwn == "walk"){
					this.runner = false;
					this.lobby.walkCheckbox.checkBox.gotoAndStop(1);
				}else{
					this.lobby.walkCheckbox.checkBox.disabled.visible = false;
				}
			}else if(feature == "deactivate"){
				if(this.changeFeatureByMyOwn == "deactivate"){
					this.defuser = false;
					this.lobby.deactivateCheckbox.checkBox.gotoAndStop(1);
				}else{
					this.lobby.deactivateCheckbox.checkBox.disabled.visible = false;
				}
			}
			this.changeFeatureByMyOwn = "";
		}
		public function removeMoveListener():void {
			stage.removeEventListener(Event.ENTER_FRAME, moveCharacter);
		}
		public function addMoveListener():void {
			stage.addEventListener(Event.ENTER_FRAME, moveCharacter);
		}
		public function getRunner():Boolean {
			return this.runner;
		}
		public function getTrapFinder():Boolean {
			return this.trapFinder;
		}
		public function getDefuser():Boolean {
			return this.defuser;
		}

		public function featureNotSelectable() : void {
			this.changeFeatureByMyOwn = "";
			this.lobby.error.text = "Cannot select feature";
		}
		
		private function joinNewGameClick(event:MouseEvent):void{
			
			//Clean lobby
			// join new game
			this.players = null;
			this.runner = false;
			this.viewer = false;
			this.defuser = false;
			this.riddler = false;
			this.trapFinder = false;
			
			points = 0;
			map = null;
			SPEED = 5;
			goalReached = false;
			keypressed=false;
			key = 0;
			
			startVal=COMPLETE/100;
			proz=0;
			bomb = null;
			defusing = false;
		
			bombNr = -1;
			received = true;
			changeFeatureByMyOwn= "";
			defusedBomb=0;
			
			
			this.socket.send("login\n");
			this.socket.send(employeName + "\n");
			this.socket.send(company+"\n");
			this.gameOver.visible = false;
		}

		public function connectedToServer() : void {
			this.connectScreen.connectMC.visible=true;
			this.registerScreen.visible = true;
			this.connectScreen.visible = false;
		}

		public function quizTimeStarted() : void {
			
			if(riddler){
				stage.addChild(quizenginge);
				this.quizTimer.reset();
				this.questionTime =60;
				this.quizQuestionTimer.start();
			}else{
				stage.addChild(waitingquiz);
			}
			this.quizTime = true;
		}

		public function quizTimeEnded() : void {
			if(riddler){
				this.questionTime=60;
				trace("bevor remove");
				stage.removeChild(quizenginge);
				trace("after remove");
				this.quizenginge.nextQuestion();
				this.quizQuestionTimer.reset();
				this.quizTimer.start();
				this.quizNoQuestionSelected = true;
			}else{
				stage.removeChild(waitingquiz);
			}
			this.quizTime = false;
			
		}

		
		
		
		
		
		
		
		
		public function getQuizQuestionTimer():Timer{
			return this.quizQuestionTimer;
		}
		
		public function setQuizNoQuestionSelected(bool:Boolean):void{
			this.quizNoQuestionSelected = bool;
		}
		

		function updateBombArray(pos:int):void {
			this.bombArray.splice(pos, 1);
		}
		public function getBombArray():Array {
			return this.bombArray;
		}
		public function updateGameTimer():void {
			this.gameTimer++;
			var std:int = int(this.gameTimer / 3600); 
            var min:int = int(int(this.gameTimer % 3600)/60); 
            var sec:int = this.gameTimer % 60;
			this.timerPanel.timePanel.numFeld.text = (std < 9 ? "0" + std : std) + ":" + (min < 9 ? "0" + min : min) + ":" + (sec < 9 ? "0" + sec : sec);
		}

		public function setPoints(i : int) : void {
			this.points = i;
		}
		
		public function initFeatures():void{
			if(!riddler){
				this.features.raetsel.visible = false;
			}
			
			if(!defuser){
				this.features.entschaerfen.visible = false;
			}
			
			if(!viewer){
				this.features.sehen.visible = false;
			}
			
			if(!trapFinder){
				this.features.fallen.visible = false;
			}
			
			if(!this.runner){
				this.features.laufen.visible = false;
			}
		}
	}
}